package com.tsh.chat.service.impl;

import com.fasterxml.jackson.core.JacksonException;
import com.tsh.chat.domain.Personality;
import com.tsh.chat.domain.PromptHistory;
import com.tsh.chat.mapper.PersonalitySimulatorMapper;
import com.tsh.chat.service.PromptService;
import com.tsh.chat.util.ChatUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

@Service
public class PromptServiceImpl implements PromptService {
    @Autowired
    PersonalitySimulatorMapper personalitySimulatorMapper;

    /**
     * 根据数据库中的人设描述记录重构人设
     */
    @Override
    public Personality rebuildPersonality(int userId){
        List<PromptHistory> promptHistoryList = personalitySimulatorMapper.selectPromptHistoryByUserId(userId);
        Personality personality = new Personality();
        Date date = new Date();
        personality.setUserId(userId);
        personality.setDescription("");
        personality.setAchievement("");
        personality.setRelationship("");
        personality.setDate(date);
        for(PromptHistory promptHistory : promptHistoryList){
            String prompt = promptHistory.getPrompt();
            personality = updatePersonality(personality, prompt);
        }
        return personality;
    }

    /**
     * 根据人设描述prompt更新人设
     */
    @Override
    public Personality updatePersonality(Personality personality, String prompt){
        Personality newPersonality = new Personality();
        Date nowadays = new Date();
        Date oldTime = personality.getDate();
        String oldDesc = personality.getDescription();
        String oldAchieve = personality.getAchievement();
        String oldRelation = personality.getRelationship();
        try{
            String characterDesc = ChatUtil.updateCharacterDescSSE(oldDesc, prompt, oldTime, nowadays);
            String characterAchieve = ChatUtil.updateCharacterAchievementSSE(oldAchieve, prompt, oldTime, nowadays);
            String characterRelation = ChatUtil.updateCharacterRelationSSE(oldRelation, prompt, oldTime, nowadays);
            newPersonality.setUserId(personality.getUserId());
            newPersonality.setDescription(characterDesc);
            newPersonality.setAchievement(characterAchieve);
            newPersonality.setRelationship(characterRelation);
            newPersonality.setDate(nowadays);
            return newPersonality;
        }catch (JacksonException e){
            return null;
        }
    }
}
